import Sequelize from 'sequelize';
const { BIGINT } = Sequelize;
// import Sequelize, { BIGINT } from 'sequelize';
import sequelize from './connectDatabase.js'; /* 连接数据库 */

function defineModel (name, attributes) {
  var attrs = {};
  for (let key in attributes) {
    let value = attributes[key];
    if (typeof value === 'object' && value['type']) {
      value.allowNull = value.allowNull || false;
      attrs[key] = value;
    } else {
      attrs[key] = {
        type: value,
        allowNull: false
      };
    }
  }
  /* 主键自增 */
  attrs.id = {
    type: BIGINT,
    autoIncrement: true,
    primaryKey: true
  };
  attrs.createdTime = {
    type: BIGINT,
    allowNull: false,
    /* 修改列名 */
    field: 'create_time'
  };
  attrs.updatedTime = {
    type: BIGINT,
    allowNull: false,
    field: 'updated_time'
  };
  attrs.version = {
    type: BIGINT,
    allowNull: false
  };
  return sequelize.define(name, attrs, {
    tableName: name,
    timestamps: false,
    hooks: {
      beforeValidate: function (obj) {
        let now = Date.now();
        if (obj.isNewRecord) {
          obj.createdTime = now;
          obj.updatedTime = now;
          obj.version = 0;
        } else {
          /* 每次修改 都设置修改时间，与版本号 */
          obj.updatedTime = Date.now();
          obj.version++;
        }
      }
    }
  });
}

const TYPES = ['STRING', 'INTEGER', 'BIGINT', 'TEXT', 'DOUBLE', 'DATEONLY', 'BOOLEAN'];

var exp = {
  defineModel: defineModel,
  sync: () => {
    console.log(process.env.NODE_ENV);
    // only allow create ddl in non-production environment:
    if (process.env.NODE_ENV !== 'production') {
      // sequelize.sync({
      //     force: true
      // });
      sequelize.sync({
        force: true
      }).then(() => {
        console.log('数据库表异步初始化成功');
        process.exit(0);
      }).catch((e) => {
        console.log(`failed:${e}`);
        process.exit(0);
      });
    } else {
      throw new Error('Cannot sync() when NODE_ENV is set to \'production\'.');
    }
  }
};

for (let type of TYPES) {
  exp[type] = Sequelize[type];
}

export default exp;